package com.wang.friend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.wang.api.RemoteJudgeService;
import com.wang.api.domain.UserExeResult;
import com.wang.api.domain.JudgeSubmitDTO;
import com.wang.api.domain.UserQuestionResultVO;
import com.wang.common.security.exception.ServiceException;
import com.wang.friend.domain.question.Question;
import com.wang.friend.domain.question.QuestionCase;
import com.wang.friend.domain.user.UserSubmit;
import com.wang.friend.domain.user.dto.UserSubmitDTO;
import com.wang.friend.domain.question.es.QuestionES;
import com.wang.friend.elasticsearch.QuestionRepository;
import com.wang.friend.mapper.question.QuestionMapper;
import com.wang.friend.mapper.user.UserSubmitMapper;
import com.wang.friend.rabbit.JudgeProducer;
import com.wang.friend.service.IUserQuestionService;
import com.wang.common.core.constants.Constant;
import com.wang.common.core.domain.R;
import com.wang.common.core.enums.ProgramType;
import com.wang.common.core.enums.QuestionResType;
import com.wang.common.core.enums.ResultCode;
import com.wang.common.core.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private RemoteJudgeService remoteJudgeService; //需要在启动方法类中加上@EnableFeignClients

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        //判断提交代码的类型
        Integer programType = userSubmitDTO.getProgramType();

        if (ProgramType.JAVA.getValue().equals(programType)){
            //构造提交代码对象 JudgeSubmitDTO
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            //调用判题功能服务,并返回结果
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }

        //目前只支持Java语言,其他语言不支持
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        //1.判断提交代码的类型
        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)){
            //2.构造提交代码对象JudgeSubmitDTO
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            //3.把用户提交的代码发送到消息队列
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        //目前只支持Java语言,其他语言不支持
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        //之所以要加上currentTime是为了避免获取到历史竞赛的结果

        //1.从ThreadLocal中获取用户id
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);

        //2.获取当前用户的提交记录
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);

        UserQuestionResultVO resultVO = new UserQuestionResultVO();
        if (userSubmit == null) {
            //如果提交记录为空,则返回判题中
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }else{
            //如果不为空,封装判题结果并返回
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeResult())){
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeResult(), UserExeResult.class));
            }
        }
        return resultVO;
    }

    /**
     * 拼接主方法和用户提交代码
     * @param userCode 用户提交代码
     * @param mainFunc 主方法
     * @return 返回拼接之后的结果
     */
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }

    /**
     * 把userSubmitDTO转换为JudgeSubmitDTO
     * @param userSubmitDTO userSubmitDTO
     * @return JudgeSubmitDTO
     */
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO){
        Long questionId = userSubmitDTO.getQuestionId();
        //首先从ES中获取当前题目的信息
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null){
            //如果存在,把其中的属性全部复制过来
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else{
            //如果不存在,从数据库中刷新
            Question question = questionMapper.selectById(questionId);
            questionES = new QuestionES();
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        //之后把JudgeSubmitDTO中其他的字段值补齐
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constant.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());

        //注意要拼接好主方法和用户提交的代码
        judgeSubmitDTO.setUserCode(codeConnect(userSubmitDTO.getUserCode(),questionES.getMainFuc()));
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());

        //使用JSON工具把字符串转换为list
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);

        //把测试用例的输入和输出分开
        List<String> inputList = new ArrayList<>();
        List<String> outputList  = new ArrayList<>();

        for (QuestionCase questionCase : questionCaseList){
            inputList.add(questionCase.getInput());
            outputList.add(questionCase.getOutput());
        }

        judgeSubmitDTO.setInputList(inputList);
        judgeSubmitDTO.setOutputList(outputList);

        return judgeSubmitDTO;
    }
}
